<template>
  <!-- 添加|修改SPU的解构 -->
  <el-form>
    <el-form-item label="SPU名称">
      <el-input placeholder="请你输入SPU名称" v-model="spuParams.spuName "></el-input>
    </el-form-item>
    <el-form-item label="SPU品牌">
      <el-select placeholder="请选择" v-model="spuParams.tmId">
        <el-option :label="item.tmName" v-for="(item,index) in allTradeMarkArr" :value="item.id"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="SPU描述">
      <el-input type="textarea" v-model="spuParams.description"></el-input>
    </el-form-item>
    <el-form-item label="SPU图片">
      <el-upload :file-list="imgListArr" action="/api/admin/product/fileUpload" list-type="picture-card"
        :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :on-success="handleSuccess">
        <el-icon>
          <Plus />
        </el-icon>
      </el-upload>

      <el-dialog v-model="dialogVisible">
        <img w-full :src="dialogImageUrl" alt="Preview Image" />
      </el-dialog>
    </el-form-item>

    <el-form-item label="销售属性">
      <el-select v-model="unSaleAttrIdAndName"
        :placeholder="unSelectSaleAttr.length>0?`您还有${unSelectSaleAttr.length}未选择`:`没得选啦`">
        <el-option :label="item.name" :value="`${item.id}:${item.name}`" v-for="(item,index) in unSelectSaleAttr">
        </el-option>
      </el-select>
      <el-button style="margin-left: 10px" type="primary" size="default" :icon="Plus" :disabled="!unSaleAttrIdAndName"
        @click="addSaleAttr">添加销售属性值</el-button>
      <el-table border stripe style="margin: 10px 0px" :data="spuHasSaleAttrArr">
        <el-table-column label="序号" type="index" align="center" width="80"></el-table-column>
        <el-table-column label="属性名" width="120" prop="saleAttrName"></el-table-column>
        <el-table-column label="属性值名称列表">
          <!-- 底下的row:销售属性对象 -->
          <template #="{ row, $index }">
            <!-- 利用el-tag展示销售属性值 -->
            <el-tag style="margin:0px 5px" v-for="(saleValue,index) in row.spuSaleAttrValueList" :key="saleValue.id"
              class="mx-1" closable @close="row.spuSaleAttrValueList.splice(index,1)"
              :type="saleValue.id%2==0?'success':'warning'">
              {{ saleValue.saleAttrValueName }}
            </el-tag>
            <el-input placeholder="请输入属性值" clearable style="width:100px" v-if="row.flag1" @blur="changLook(row)"
              v-model="row.inputValue" :ref="(vc)=>inputArr[$index] = vc"></el-input>
            <el-button type="primary" size="small" @click="changEdit(row,$index)" :icon="Plus" v-else></el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="120">
          <template #="{row,$index}">
            <el-button type="danger" size="small" :icon="Delete" @click="spuHasSaleAttrArr.splice($index,1)">
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-button type="primary" size="default" @click="saveList">保存</el-button>
      <el-button size="default" @click="cancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>
<script setup lang="ts">
//引入组合式API
import { ref, reactive, computed, nextTick } from "vue";
import { Plus, Delete } from "@element-plus/icons-vue";
import { ElMessage, type UploadProps, type UploadUserFile } from "element-plus";
import { reqAllaTradeMark, reqAllSaleAttr, reqImgList, reqSpuHasSaleAttr, reqAddOrUpdateSpu } from '@/api/product/spu/spu.ts'
//照片墙相关的代码
//存储预览图片地址
const dialogImageUrl = ref("");
//控制对话框显示与隐藏
const dialogVisible = ref(false);

//删除图片回调
const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  //第一个参数:uploadFile,删除掉的图片信息  第二个参数:uploadFiles删除完毕剩下图片的信息
  imgListArr.value = uploadFiles;
};
//预览回调
const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  //存储当前用户预览图片地址
  dialogImageUrl.value = uploadFile.url!;
  //展示对话框
  dialogVisible.value = true;
};

//图片上传成功的回调
const handleSuccess = (response, uploadFile, uploadFiles) => {
  //前两个参数:图片上传成功的信息
  //最后的参数:图片上传成功以后，照片墙全部图片数据
  imgListArr.value = uploadFiles
}
//已有SPU下的全部品牌数据
let allTradeMarkArr = ref([]);
//获取已有SPU下照片墙的数据
let imgListArr = ref([]);
//获取已有SPU，拥有销售属性
let spuHasSaleAttrArr = ref([]);
//获取全部销售属性[不管任何SPU销售属性最多三个]
let allSaleAttrArr = ref([]);
//定义将来添加SPU|修改SPU需要携带给服务器参数
let spuParams = ref({

})
//收集SPU还未选择销售属性ID与名字
let unSaleAttrIdAndName = ref('');
//触发自定义事件
let emit = defineEmits(["changeScene"]);

const reqAllList = async (row) => {
  try {
    console.log(row);
    //父组件:传递过来已有SPU信息存储
    spuParams.value = row;
    let reasult = await reqAllaTradeMark()//获取全部品牌接口
    let reasult1 = await reqAllSaleAttr()//全部销售属性接口
    let reasult2 = await reqImgList(row.id)//已有SPU照片墙的接口
    let reasult3 = await reqSpuHasSaleAttr(row.id)//获取【SPU】已有的销售苏醒
    console.log(reasult);
    console.log(reasult1);
    console.log(reasult2);
    console.log(reasult3);
    //存储全部品牌
    allTradeMarkArr.value = reasult;
    //存储照片墙的数据
    //由于服务器返回的数据格式并非人家照片墙需要的需要[对象K不符合]
    //当服务器数据返回需要对数据进行处理
    imgListArr.value = reasult2.map(item => {
      return {
        name: item.imgName,
        url: item.imgUrl
      }
    })
    //存储已有销售属性
    spuHasSaleAttrArr.value = reasult3;
    //获取全部销售属性
    allSaleAttrArr.value = reasult1;
  } catch (error) {
  }


}
//点击添加SPU的时候，当前子组件发请求(两个:获取全部品牌|全部销售属性)
const initAddSpu = async (c3Id: string | number) => {
  //添加SPU追加三级分类ID
  spuParams.value.category3Id = c3Id;
  //获取全部品牌数据
  let ps1 = reqAllaTradeMark();
  //获取全部销售属性
  let ps2 = reqAllSaleAttr();
  let result = await Promise.all([ps1, ps2]);
  //存储全部品牌
  allTradeMarkArr.value = result[0];
  //获取全部销售属性
  allSaleAttrArr.value = result[1];
};
const unSelectSaleAttr = computed(() => {
  let reasult = []
  for (let i = 0; i < allSaleAttrArr.value.length; i++) {
    let flag = false
    for (let a = 0; a < spuHasSaleAttrArr.value.length; a++) {
      if (allSaleAttrArr.value[i].name == spuHasSaleAttrArr.value[a].saleAttrName) {
        flag = true
        break
      }
    }
    if (!flag) {
      reasult.push(allSaleAttrArr.value[i])
    }
  }
  return reasult
})
//点击添加销售属性按钮回调
const addSaleAttr = () => {
  //整理参数
  //新增的销售属性ID与名字
  const [baseSaleAttrId, saleAttrName] = unSaleAttrIdAndName.value.split(":");
  console.log(baseSaleAttrId,saleAttrName);
  //服务器需要销售属性对象
  let newSaleAttr = { baseSaleAttrId, saleAttrName, spuSaleAttrValueList: [] };
  console.log(newSaleAttr);
  //向SPU已有的数组里面追加新增销售是属性
  spuHasSaleAttrArr.value.push(newSaleAttr);
  //清空下拉框的数据
  unSaleAttrIdAndName.value = '';
}
let inputArr = ref([]);
let flag = ref(0)
const changEdit = (row, $index) => {
  flag.value = 1
  row.flag1 = true
  row.inputValue = ''
  //点击div切换显示el-input，需要聚焦
  nextTick(() => {
    inputArr.value[$index].focus();
  })
}
const changLook = (row) => {
  row.flag1 = false
  if (row.inputValue.trim() == '') {
    ElMessage({
      type: 'error',
      message: '不能空'
    })
    return
  }
  let request = row.spuSaleAttrValueList.find(item => {
    return item.saleAttrValueName === row.inputValue;
  })
  if (request) {
    ElMessage({
      type: 'error',
      message: '属性值名称不能重复'
    });
    //清空最新收集同名属性值
    row.inputValue = '';
    return;
  }
  let newSaleattrVal = {
    baseSaleAttrId: row.baseSaleAttrId,
    saleAttrValueName: row.inputValue
  }
  row.spuSaleAttrValueList.push(newSaleattrVal)
  row.inputValue = ''
}

const saveList = async () => {
  spuParams.value.spuImageList = imgListArr.value.map(item => {
    return {
      imgName: item.name,
      imgUrl: (item.response && item.response.data) || item.url,
    }
  })
  spuParams.value.spuSaleAttrList = spuHasSaleAttrArr.value;
  //发请求:修改|添加
  try {
    await reqAddOrUpdateSpu(spuParams.value);
    ElMessage({
      type: "success",
      message: spuParams.value.id ? "修改成功" : "添加成功",
    });
    emit('changeScene', {
      sences: 0,
      flag: spuParams.value.id ? "update" : "add",
    })
    empty()
  } catch (error) {

  }
}

const empty = () => {
  //获取已有SPU下照片墙的数据
  imgListArr.value = []
  //获取已有SPU，拥有销售属性
  spuHasSaleAttrArr.value = []
  spuParams.value = {}
}

const cancel = () => {
  emit('changeScene', {
    sences: 0,
    flag: spuParams.value.id ? "update" : "add",
  })
  empty()
}
defineExpose({
  reqAllList,initAddSpu
})
</script>

<style scoped>

</style>